import cv2
import datetime

# 打开本地摄像头
cap = cv2.VideoCapture(0)

width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# 设置编解码器
fourcc = cv2.VideoWriter_fourcc(*"mp4v")

# 定义一个变量，用于记录帧速率
fps = 20.0

# 定义一个变量，用于记录每个视频的长度（以秒为单位）
video_length = 1 * 60 * 60  # 1 hour

# 定义一个变量，用于记录保存的文件名前缀
filename_prefix = "/Users/jiangtao/Movies/opencv/video_"

# 定义一个计数器，用于记录已经写入的帧数
frame_count = 0

# 定义一个变量，用于记录视频的序号
video_number = 1

# 持续捕获并保存视频帧
while(True):
    # 检查是否需要开始一个新的视频文件
    if frame_count == 0:
        # 创建输出视频文件
        filename = filename_prefix + str(video_number) + "_" + datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".mp4"
        out = cv2.VideoWriter(filename, fourcc, fps, (width, height))
        print("Start recording " + filename)

    # 读取视频帧
    ret, frame = cap.read()

    # 检查是否到达视频长度的末尾
    if frame_count >= fps * video_length:
        # 释放资源
        out.release()
        cv2.destroyAllWindows()
        print("Finish recording " + filename)

        # 重置计数器和视频序号
        frame_count = 0
        video_number += 1
    else:
        # 处理帧
        # ...

        # 写入帧到输出视频文件
        out.write(frame)

        # 显示帧
        cv2.imshow('frame',frame)

        # 按 'q' 键退出循环
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        # 更新计数器
        frame_count += 1

# 释放资源
cap.release()
cv2.destroyAllWindows()
